<template>
  <div :id="id" :style="{ height:height,width:width }" />
</template>

<script>
import echarts from "echarts";
export default {
  props: {
    id: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "420px",
    },
    data: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      chart: null,
      hotWordName:[],
      hotWordData:[]
    };
  },
  mounted() {
    console.log(this.height)
    this.dataManage()
    this.initChart();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart = null;
  },
  methods: {
    dataManage(){
      if (this.data.length === 0) {
        return;
      }
      this.hotWordName = [];
      this.hotWordData = []
      this.data.forEach((item, index) => {
        this.hotWordName.push(item.name);
        this.hotWordData.push(item.value)
      });
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id));
      const option = {
        backgroundColor: "#fff", //背景颜色
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "none",
          },
        },
        yAxis: {
          type: "category",
          axisLine: {
            show: false, //坐标线
          },
          axisTick: {
            show: false, //小横线
          },
          axisLabel: {
            interval: 0,
            margin: 120,
            textStyle: {
              align: "left",
              baseline: "middle",
            },
          },
          data: this.hotWordName
        },

        xAxis: {
          show: false,
        },
        grid: {
          top: "0px",
          left: "120px",
          bottom: "0px",
        },
        series: [
          {
            /* data: [120, 200, 150, 80, 70, 110, 130], */
            type: "bar",
            barWidth: "10px",
            backgroundStyle: {
              color: "rgba(220, 220, 220, 0.4)",
              barBorderRadius: [30, 30, 30, 30], //圆角大小
            },
            label: {
              show: true,
              position: "right", //每一条的数据位置
              offset: [-30, -15],
            },
            itemStyle: {
              normal: {
                barBorderRadius: 30,
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  {
                    offset: 0,
                    color: "rgb(3,123,255,1)",
                  },
                  {
                    offset: 1,
                    color: "rgb(59,189,244,1)",
                  },
                ]),
              },
            },
            data: this.hotWordData,
          },
        ],
      };
      this.chart.setOption(option);
    },
  },
};
</script>